<?php
namespace frontend\controllers;

use Yii;
use common\models\GameVersion;
use yii\helpers\BaseJson;
use common\models\Game;
use yii\filters\VerbFilter;
use common\models\Article;
use common\models\GameInfo;
use common\models\GameWithType;
use common\models\GameType;
use yii\base\Behavior;

/**
 * 游戏
 *
 * @author jois
 */
class GameController extends BaseController
{
    // 定义每一页的数量
    public $limit = 5;
    // 此limit要和ArticleController的$ajax_limit相同
    public $article_limit = 8;

    /**
     * 请求方法过滤
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'detail' => [
                        'get'
                    ],
                    'ajax-article-list' => [
                        'post'
                    ],
                    'ajax-list' => [
                        'get'
                    ]
                ]
            ]
        ];
    }

    public function beforeAction($action)
    {
        if (in_array($action->id, [
            'download'
        ])) {
            $this->enableCsrfValidation = false;
        }
        return parent::beforeAction($action);
    }

    /**
     * 首页/游戏
     */
    public function actionIndex()
    {
        // 所有游戏，条件为已推荐未删除的游戏
        $games = GameVersion::find()->where("is_first=1")
            ->joinWith([
            'game.types'
        ])
            ->orderBy("game.sort_num desc")
            ->limit($this->limit)
            ->all();

        // 所有一级游戏类型，即游戏分类
        $game_types = GameType::topNode()->all();

        return $this->render('index', compact('games', 'game_types'));
    }

    /**
     * 异步获取游戏列表
     */
    public function actionAjaxList()
    {
        // 验证page参数
        $page = (int) Yii::$app->request->get('page', 0);
        $type_id = (int) Yii::$app->request->get('type_id', 0);
        if ($page > 1 && Yii::$app->request->isAjax) {
            // 开始获取数据
            // TODO:本想给game加上isdel=0 and is_comment=1的条件，但是和game.types一起使用就会使原先limit=5个的变成4个
            if ($type_id > 0) {
                $games = GameVersion::find()->where("is_first=1")
                    ->joinWith([
                    'game.types' => function ($query) use($type_id)
                    {
                        $query->where("game_types.type_id={$type_id}");
                    }
                ])
                    ->orderBy("game.sort_num desc")
                    ->offset(($page - 1) * $this->limit + 1)
                    ->limit($this->limit)
                    ->asArray()
                    ->all();
            } else {
                $games = GameVersion::find()->where("is_first=1")
                    ->joinWith([
                    'game.types'
                ])
                    ->orderBy("game.sort_num desc")
                    ->offset(($page - 1) * $this->limit + 1)
                    ->limit($this->limit)
                    ->asArray()
                    ->all();
            }
            return BaseJson::encode($games, true);
        }
        return BaseJson::encode('获取失败，参数或请求方法异常');
    }

    /**
     * 游戏资讯正文显示
     */
    public function actionDetail()
    {
        $id = (int) Yii::$app->request->get('version_id', 0);
        if ($id) {
            // 游戏信息
            $model = GameVersion::find()->with('game')
                ->where("id={$id}")
                ->one();
            if ($model->game) {
                $types = $model->game->types;
            }

            // 游戏相册，拷贝92fox外网代码
            $info = GameInfo::find()->select('game_album,seo_keyword,seo_description')
                ->where("game_id=" . $model->game_id)
                ->one();
            preg_match_all('/<img(.*?)\/>/i', $info->game_album, $match);
            $album = "";
            $same_games = $news = $acticity = null;
            $i = 1;
            foreach ($match[0] as $key => $value) {
                // by jois add,图片地址还这么多个吗？连旧的http://www.92fox.com/detail/105/都无法显示这些图片，没辙
                // $value = preg_replace('/src=\"\/data/', "src=" . Yii::$app->params['pipawImgPath'] . "data", $value);
                preg_match_all('/height=.*? /i', $value, $match2);
                if ($match2 && $match2[0]) {
                    $lvTmp = str_replace($match2[0][0], '', $value);
                } else
                    $lvTmp = $value;

                preg_match_all('/width=.*? /i', $lvTmp, $match2);
                if ($match2 && $match2[0])
                    $lvTmp2 = str_replace($match2[0][0], '', $lvTmp);
                else
                    $lvTmp2 = $lvTmp;

                $album .= "<li>{$lvTmp2}</li>";

                $i ++;
                if ($i == 5)
                    break;
            }
            // 游戏新闻资讯信息
            $news = Article::find()->where("kind=" . Article::KIND_NEWS . " and game_id=" . $model->game_id)
                ->orderBy("id desc")
                ->limit(5)
                ->all();
            // 游戏活动资讯信息
            $acticity = Article::find()->where("kind=" . Article::KIND_ACTIVITY . " and game_id=" . $model->game_id)
                ->orderBy("id desc")
                ->limit(5)
                ->all();

            // 同类游戏，抓出这个类型对应的游戏
            $type_ids = GameWithType::find()->select('type_id')
                ->where("game_id=" . $model->game_id)
                ->column();
            if (! empty($type_ids)) {
                $same_games = GameVersion::find()->where("is_first=1")
                    ->joinWith([
                    'game.types' => function ($query) use($type_ids)
                    {
                        $query->where([
                            "in",
                            "game_types.type_id",
                            $type_ids
                        ]);
                    }
                ])
                    ->orderBy("rand()")
                    ->limit(4)
                    ->all();
            }
            return $this->render('detail', compact('model', 'info', 'types', 'news', 'acticity', 'album', 'same_games'));
        }
        throw new \yii\web\MethodNotAllowedHttpException('操作异常，参数获取失败');
        return FALSE;
    }

    /**
     * 游戏新闻列表，通过详细页的更多点击进来
     */
    public function actionArticleList()
    {
        $id = (int) Yii::$app->request->get('version_id', 0);
        $kind = Yii::$app->request->get('kind', '');
        if ($id) {
            $model = GameVersion::find()->with('game')
                ->where("id={$id}")
                ->one();
            $types = Game::findOne($model->game_id)->types;

            // 游戏对应文章列表
            $limit = $this->article_limit;
            $articles = Article::find()->where("game_id=" . $model->game_id)
                ->orderBy("sort desc")
                ->limit($limit)
                ->all();

            return $this->render('article-list', compact('model', 'articles', 'types', 'limit', 'kind'));
        }
        throw new \yii\web\MethodNotAllowedHttpException('操作异常，参数获取失败');
        return FALSE;
    }

    /**
     * 游戏列表，通过分类点击进来
     */
    public function actionList()
    {
        // $id = (int) Yii::$app->request->get('type_id', 0);
        $alias = Yii::$app->request->get('type_alias', '');
        if (! empty($alias)) {
            // 分类对应游戏列表
            $limit = $this->limit;
            $type = GameType::find()->where('alias=:alias')
                ->addParams([
                'alias' => $alias
            ])
                ->one();
            $id = $type->type_id;

            // 找出这个类型的前五个游戏
            $ostype = getostype();
            if ((int) $ostype == 1 || (int) $ostype == 2) {
                $games = GameVersion::find()->where("is_first=1 and mobileos_type_id={$ostype}")
                    ->joinWith([
                    'game.types' => function ($query) use($id)
                    {
                        $query->where("game_types.type_id={$id}");
                    }
                ])
                    ->orderBy("game.sort_num desc")
                    ->limit($limit)
                    ->all();

                return $this->render('list', compact('type', 'games', 'limit'));
            }
            throw new \yii\web\MethodNotAllowedHttpException('操作异常，手机系统类型获取失败');
            return FALSE;
        }
        throw new \yii\web\MethodNotAllowedHttpException('操作异常，参数获取失败');
        return FALSE;
    }

    /**
     * 明细页点击下载，对应游戏的下载数量加一，异步
     */
    public function actionDownload()
    {
        $game_version_id = (int) Yii::$app->request->get('game_version_id', 0);
        if ($game_version_id > 0) {
            // 检测游戏是否存在
            $game_version = GameVersion::findOne($game_version_id);
            $game = $game_version->game;
            if (is_object($game_version) && is_object($game)) {
                // 检测下载链接对应的安装包是否存在
                $down_link = $game_version->soft_url;
                $down_rate = 50;
                $fileinfo = pathinfo($down_link);
                if (! is_null($fileinfo['extension'])) {// && $fileinfo['extension'] == 'apk'
                    // 检测可下载，则下载数量加一
                    $game->game_downclick = $game->game_downclick + 1;
                    $game->save();
                    var_dump($down_link);die;
                    header('Content-Description: File Transfer');
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment; filename=' . $fileinfo['basename']);
                    header('Content-Transfer-Encoding: binary');
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate');
                    header('Pragma: public');
                    // header('Content-Length: ' . ($game_version->version_size*1024*1024));
                    ob_clean();
                    flush();
                    readfile($down_link); // 此函数可作用于远程地址，其他方法不能使用
                }
                return '游戏下载包不存在';
            }
            return '游戏不存在';
        }
        return '参数错误，下载数量无法加一';
    }
}
